<!--
 * @Description: 国际化语言选择组件
 * @Version: 2.0
 * @Autor: lhl
 * @Date: 2021-06-20 20:14:06
 * @LastEditors: lhl
 * @LastEditTime: 2021-06-20 21:59:46
-->
<template>
  <div>
    <el-dropdown trigger="click">
      <div>{{ languageName }}</div>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item v-for="item in languages" :key="item.value">
            <div @click="handleSetLanguage(item)">{{ item.name }}</div>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script lang="ts">
import { useStore } from 'vuex'
import { computed, defineComponent, reactive, toRefs } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'

type Language = {
  name: string
  value: string
}

export default defineComponent({
  setup() {
    const store = useStore()
    const { locale, t } = useI18n()
    const state = reactive({
      languageName: '国际化',
      languages: [
        { name: '中文', value: 'zh-cn' },
        { name: '中文繁体', value: 'tw-cn' },
        { name: 'English', value: 'en' },
        { name: '日本語', value: 'ja' }
      ] as Array<Language>
    })
    const methods = {
      handleSetLanguage: (lang: Language) => {
        locale.value = lang.value
        state.languageName = lang.name
        store.commit('setUpLanguage', lang.value)
        ElMessage({
          message: 'Switch Language Success',
          type: 'success'
        })
      }
    }
    const language = computed(() => {
      return store.getters.language
    })
    return {
      t,
      ...methods,
      ...toRefs(state),
      language
    }
  }
})
</script>

<style lang="scss" scoped></style>
